﻿package crochet.core;

/*
 Copyright 2011 Intuitive Solutions

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;

import crochet.core.policy.IExecutionPolicy;

public class SequentialScheduler implements IScheduler, Runnable {
	protected Thread tThread;
	protected boolean bIterate;
	protected Semaphore sSemaphore;
	protected Queue<IExecutionPolicy> qProcessQueue;
	protected IExecutionPolicy epCloneableExecutionPolicy;

	public SequentialScheduler(IExecutionPolicy epCloneableExecutionPolicy) {
		bIterate = true;
		sSemaphore = new Semaphore(10000);
		this.epCloneableExecutionPolicy = epCloneableExecutionPolicy;
		qProcessQueue = new ConcurrentLinkedQueue<IExecutionPolicy>();
		tThread = new Thread(this);

		epCloneableExecutionPolicy.setRootScheduler(this);

		tThread.start();
	}

	public void run() {
		while (bIterate) {
			try {
				sSemaphore.acquire();

				synchronized (qProcessQueue) {
					if (bIterate) {
						qProcessQueue.poll().execute(this);
					}
				}
			} catch (Exception e) {
			}
		}
	}

	public IExecutionPolicy getCloneableExecutionPolicy() {
		return epCloneableExecutionPolicy;
	}

	public void schedule(IExecutionPolicy epExecutionPolicy) {
		synchronized (qProcessQueue) {
			qProcessQueue.add(epExecutionPolicy);
		}

		sSemaphore.release();
	}

	public void schedule(ISchedulerDelegate sdSchedulerDelegate) {
		schedule(sdSchedulerDelegate, null);
	}

	public void schedule(ISchedulerDelegate sdSchedulerDelegate,
			IExceptionHandlerDelegate ehdExceptionHandlerDelegate) {
		schedule(epCloneableExecutionPolicy.clone(sdSchedulerDelegate,
				ehdExceptionHandlerDelegate));
	}

	public void dispose() {
		bIterate = false;
		sSemaphore.release();

		try {
			tThread.join(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		sSemaphore = null;
		qProcessQueue = null;
	}
}
